import jwt from 'jsonwebtoken'
import {converterT2S,converterS2T} from './convertWord/index.js'
// import * as OpenCC from 'opencc-js';

const secretOrkey = 'activity'

/**
 * 
 * @param {string} params 
 * @returns 生成jwt
 */
function generateToken(params) {
  let token = jwt.sign({
    data: params
  }, secretOrkey, { expiresIn: `${(Date.now() / 1000) + (60 * 60 * 24 * 30)}` })
  return token
}

/**
 * 
 * @param {string} params 
 * @returns 解析jwt
 */
function parseToken(params) {
  var { data } = jwt.decode(params)

  return data
}

/**
 * 
 * @param {number} time ms
 * @returns sleep等待时间
 */
async function sleep(time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, time);
  })
}

/**
 * 
 * @param {number} max 
 * @returns 最大max的随机数
 */
const randomNum = (max = 10) => {
  return Math.floor(Math.random() * max)
}


/**
 * 深度克隆
 * @param {*} item 
 * @returns 
 */
const deepClone = (item) => {
  if (!item) { return item; } // null, undefined values check

  var types = [Number, String, Boolean],
    result;

  // normalizing primitives if someone did new String('aaa'), or new Number('444');
  types.forEach(function (type) {
    if (item instanceof type) {
      result = type(item);
    }
  });

  if (typeof result == "undefined") {
    if (Object.prototype.toString.call(item) === "[object Array]") {
      result = [];
      item.forEach(function (child, index, array) {
        result[index] = deepClone(child);
      });
    } else if (typeof item == "object") {
      // testing that this is DOM
      if (item.nodeType && typeof item.cloneNode == "function") {
        result = item.cloneNode(true);
      } else if (!item.prototype) { // check that this is a literal
        if (item instanceof Date) {
          result = new Date(item);
        } else {
          // it is an object literal
          result = {};
          for (var i in item) {
            result[i] = deepClone(item[i]);
          }
        }
      } else {
        // depending what you would like here,
        // just keep the reference, or create new object
        if (false && item.constructor) {
        } else {
          result = item;
        }
      }
    } else {
      result = item;
    }
  }

  return result;
}

/**
 * 简体转繁体
 * @param {string} word  
 * @returns 
 */
const s2t = (word) => {
  if (!word) return ''
  const cusConverter = converterS2T(word);
  return cusConverter
}
/**
 * 繁体转简体
 * @param {string} word  
 * @returns 
 */
const t2s = (word) => {
  if (!word) return ''
  const cusConverter = converterT2S(word);
  return cusConverter
}

/**
 * 数组转树形结构
 * @param {array} list 被转换的数组
 * @param {number|string} root 根节点（最外层节点）
 * @returns array
 */
function arrayToTree(list,props={key: 'id',parentKey: 'parent_id'}) {
  var map = {}, node, tree= [], i;
  for (i = 0; i < list.length; i ++) {
      map[list[i][props.key]] = list[i]; 
      list[i].children = []; 
  }
  for (i = 0; i < list.length; i += 1) {
      node = list[i];
      if (node[props.parentKey] !== null) {
          map[node[props.parentKey]]?.children.push(node);
      } else {
        // console.log('node: ', node);
          tree.push(node);
      }
  }
  return tree;
}

export {
  arrayToTree,
  s2t,
  t2s,
  randomNum,
  deepClone,
  generateToken,
  parseToken,
  sleep
}